#!/usr/bin/ruby
# encoding: utf-8
# -*- coding: utf-8 -*-
# vim:set fileencoding=utf-8:

#main.rb
#应用主程序
#使用方式：ruby main.rb video "av" "qn" #(--part p) (--name name) (--path path) 暂时不想实装，等下次build吧
#番剧已支持但没实装
require_relative "bilibilidownloader/video.rb"
require_relative "bilibilidownloader/config.rb"
require "http"
def main
  rubyv = RUBY_VERSION.split(/\./).map(&:to_i)
  if rubyv[0] < 2 || (rubyv[0]==2 && rubyv[1] < 3) then
    raise Expection,"Version Need:>2.3"
  end
  if ARGV[0] == "video" then
    aid = ARGV[1]
    qn = ARGV[2]
    cidList = Array.new
=begin
    #下次将视频标题封装进getVideoInfo中
    headers = {"User-Agent"=>"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
    html = JSON.parse(HTTP.headers(headers).get("https://api.bilibili.com/x/web-interface/view?aid=#{aid}").to_s)
    title = html["data"]["title"].gsub(/\//,"\;") # 防止视频中有“/”导致错误
    #主要是过年时懒了/_/
=end
    info = BilibiliDownloader::Video.getVideoInfo(aid)
    title = info["title"]
    info["videoList"].each do |item|
      cidList << {"cid"=>item["cid"],"page"=>item["page"],"title"=>"#{title} - #{item["part"]}"}
    end
    cidList.each do |item|
      link = BilibiliDownloader::Video.getVideoPrivate(aid,item["cid"],qn)
      #未加密api将于下个版本加入
      startTime = Time.new
      file = BilibiliDownloader::Video.downloadVideo(link,aid)
      put "Time:#{Time.new-startTime}"
      file.each_with_index do |io,index|
	File.open("#{item["title"]} \##{index+1}.flv","wb") do |afile|
	  afile.write(io.read)
	end
	io.close
      end
    end
    return 0
  end
  return 1
end

if __FILE__ == $0 then
  exit(main)
end
